#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os, sys, signal
import asyncore, asynchat, socket, threading, time

HOST = "127.0.0.1"
PORT = 54344

def DEBUG(format, *args) : print format % args

will_stop = False

def signal_stop( signo, frame ) :
    global  will_stop
    DEBUG( "SERVER catch #%d signal, would stop.", signo )
    will_stop = True
    return
    # signal_stop

class echo_handler(asynchat.async_chat) :
    def    __init__(self, connect) :
        asynchat.async_chat.__init__(self, conn=connect)
        self.__connect = connect
        self.__buf_incoming = []
        self.__terminator = "\n"
        self.set_terminator(self.__terminator)
        
    def    collect_incoming_data(self, data) :
        DEBUG('SERVER collect: >>>%s<<<', data)
        self.__buf_incoming.append(data)
    
    def    found_terminator(self) :
        DEBUG('SERVER found: >>>%s<<<', self.__buf_incoming)
        line = ''.join(self.__buf_incoming)
        self.handle(line)
        self.__buf_incoming = []
        # found_terminator()
        
    def    handle_close(self) :
        DEBUG('SERVER will close connection...')
        self.close()
        # handle_close()
        
    def    handle(self, record) :
        DEBUG('SERVER echo: %s', record)
        self.push(record + '\n')
        
    def    run(self) :
        asyncore.loop()
        
class echo_server(object):

    def run(self):
        global will_stop
        
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind((HOST, PORT))
        DEBUG('SERVER listening on %s:%d ...', HOST, PORT)
        sock.listen(1)
        connect, client = sock.accept()
        DEBUG('SERVER accept client %s', client)
        
        handler = echo_handler(connect)
        handler.run()
        
        sock.close()

def main():
    # mask signal
    signal.signal( signal.SIGTERM, signal_stop )
    if 'posix' == os.name :
        signal.signal( signal.SIGQUIT, signal_stop )

    s = echo_server()
    try :
        s.run()
    except :
        DEBUG( "SERVER interrupt : %s", `sys.exc_info()[1]` )

if __name__ == '__main__' :
    main()
    sys.exit(0)
